package com.kedacom.general.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kedacom.general.common.ResponseData;
import com.kedacom.general.feign.FeignCTserverClient;
import com.kedacom.general.param.ContextParam;
import com.kedacom.general.param.GeneratorAutoParam;
import com.kedacom.general.param.MpParam;
import com.kedacom.general.util.ConcatUtil;
import com.kedacom.general.genertor.GunsExecutor;
import com.kedacom.general.util.HttpContextUtil;
import com.kedacom.general.util.MapperConditionMapHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * 代码生成控制器
 *
 *
 * @date 2019-01-30-2:39 PM
 */
@Api("测试基础Controller")
@Controller
@Data
public class GeneratorController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.datasource.url}")
    private String jdbcUrl;


    @Value("${spring.datasource.username}")
    private String username;


    @Value("${spring.datasource.password}")
    private String password;

    @Autowired
    FeignCTserverClient feignCTserverClient;


    /**
     * 启动测试
     */
    @ApiOperation(value="测试", notes="启动测试")
    @GetMapping("")
    @ResponseBody
    public Object helloWorld() {
        return ResponseData.success("Hello");
    }




    /**
     * feign测试
     */
    @ApiOperation(value="测试", notes="Feign测试")
    @GetMapping("/feign")
    @ResponseBody
    public Object testFeign() {
        return ResponseData.success(feignCTserverClient.getLocationServer("120.6142826083374,31.3003173815332"));
    }



    /**
     * 执行代码生成
     *
     *
     * @Date 2019-01-11
     */
    @PostMapping("/execute")
    @ResponseBody
    @ApiOperation(value="代码自动生成", notes="自动生成service,impl,dao,mapper,xml")
    public Object execute(@RequestBody GeneratorAutoParam generatorAutoParam) {
        if(StringUtils.isEmpty(generatorAutoParam.getUserName())){
            generatorAutoParam.setUserName(username);
        }

        if(StringUtils.isEmpty(generatorAutoParam.getPassword())){
            generatorAutoParam.setPassword(password);
        }

        if(StringUtils.isEmpty(generatorAutoParam.getJdbcUrl())){
            generatorAutoParam.setJdbcUrl(jdbcUrl);
        }

        //获取字符串拼接数组
        String[] tableArray = new String[]{};

        if(!StringUtils.isEmpty(generatorAutoParam.getTables())){
            tableArray = ConcatUtil.getArray(generatorAutoParam.getTables());

        }

        ContextParam contextParam = new ContextParam();
        contextParam.setAuthor(generatorAutoParam.getAuthor());
        contextParam.setProPackage(generatorAutoParam.getProPackage());
        contextParam.setJdbcDriver(generatorAutoParam.getJdbcDriver());
        contextParam.setJdbcUserName(generatorAutoParam.getUserName());
        contextParam.setJdbcPassword(generatorAutoParam.getPassword());
        contextParam.setJdbcUrl(generatorAutoParam.getJdbcUrl());


        //获取临时目录
        long fileName = IdWorker.getId();
        String tempPath = System.getProperty("java.io.tmpdir") + File.separator + "yunhaiGeneration" + File.separator + fileName;
        contextParam.setOutputPath(tempPath);

        MpParam mpContextParam = new MpParam();
        mpContextParam.setGeneratorInterface(true);
        mpContextParam.setIncludeTables(tableArray);

        if (StrUtil.isNotEmpty(generatorAutoParam.getRemovePrefix())) {
            mpContextParam.setRemoveTablePrefix(new String[]{generatorAutoParam.getRemovePrefix()});
        }

        //将session中的数据传递到threadlocal中
        Map<String, String[]> attribute = (Map<String, String[]>) HttpContextUtil.getRequest().getSession().getAttribute("CONDITION_FIELDS");
        MapperConditionMapHolder.put(attribute);

        try {
            //代码生成contextParam
            GunsExecutor.executor(contextParam, mpContextParam);
        } finally {
            MapperConditionMapHolder.remove();
        }

        //打包下载代码
//        File zip = ZipUtil.zip(tempPath);
//        renderFile(fileName + ".zip", zip.getAbsolutePath());

//        return ResponseData.success(zip.getAbsolutePath());
        return ResponseData.success(tempPath);
    }

    /**
     * 返回前台文件流
     *
     * @param fileName    文件名
     * @param inputStream 输入流
     * @return
     * @author 0x0001
     */
    private ResponseEntity<InputStreamResource> renderFile(String fileName, InputStream inputStream) {
        InputStreamResource resource = new InputStreamResource(inputStream);
        String dfileName = null;
        try {
            dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", dfileName);
        return new ResponseEntity<>(resource, headers, HttpStatus.CREATED);
    }

    /**
     * 返回前台文件流
     *
     *
     * @date 2017年2月28日 下午2:53:19
     */
    private ResponseEntity<InputStreamResource> renderFile(String fileName, String filePath) {
        try {
            final FileInputStream inputStream = new FileInputStream(filePath);
            return renderFile(fileName, inputStream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件读取错误");
        }
    }

    /**
     * 返回前台文件流
     *
     *
     * @date 2017年2月28日 下午2:53:19
     */
    private ResponseEntity<InputStreamResource> renderFile(String fileName, byte[] fileBytes) {
        return renderFile(fileName, new ByteArrayInputStream(fileBytes));
    }


}
